package qin.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import qin.entity.Book;

/**
 * 图书的简单处理层
 * @author 小行星
 *
 */
public class BookDao {
	/**
	 * 存放所有的图书
	 */
	private static List<Book> books;
	private static BookDao bookDao;
	private static final Object lock = new Object();
	
	private BookDao() {};
	
	
	public static BookDao build() {
		if(null == bookDao) {
			synchronized (lock) {
				if(null == bookDao) {
					bookDao = new BookDao();
					books = new Vector<>();
					
					for(int i = 1; i <= 100; i++) {
						Book book = new Book();
						book.setNumber("ISBN-"+i);
						book.setAuthor("张三");
						book.setName("我是书");
						book.setPrice(1234.8);
						book.setPress("xxx出版社");
						books.add(book);
					}
				}
			}
		}
		
		return bookDao;
	}
	
	/**
	 * 添加图书
	 * @param book
	 */
	public void addBook(Book book) {
		books.add(book);
	}
	
	/**
	 * 修改图书
	 * @param number
	 * @param book
	 */
	public void updateBook(int idx, Book book) {
		books.set(idx, book);
	}
	
	/**
	 * 删除图书
	 * @param number
	 */
	public void deleteBook(int idx) {
		books.remove(idx);
	}
	
	/**
	 * 查询图书-通过书号
	 * @param number
	 * @return 如果没找到那么返回-1
	 */
	public int getBookIndexByNumber(String number) {
		for(int i = 0; i < books.size(); i++) {
			if(books.get(i).getNumber().equals(number)) {
				return i;
			}
		}
		return -1;
	}
	
	/**
	 * 查询图书-通过书号
	 * @param number
	 * @return 如果没找到那么返回null
	 */
	public Book getBookByNumber(String number) {
		for(int i = 0; i < books.size(); i++) {
			if(books.get(i).getNumber().equals(number)) {
				return books.get(i);
			}
		}
		return null;
	}
	
	/**
	 * 查询图书-通过出版社
	 * @param press
	 * @return
	 */
	public List<Book> getBookByPress(String press) {
		List<Book> res = new ArrayList<>();
		for(Book book : books) {
			if(book.getPress().equals(press)) {
				res.add(book);
			}
		}
		return res;
	}
	
	/**
	 * 查询图书-通过作者
	 * @param author
	 * @return
	 */
	public List<Book> getBookByAuthor(String author) {
		List<Book> res = new ArrayList<>();
		for(Book book : books) {
			if(book.getAuthor().equals(author)) {
				res.add(book);
			}
		}
		return res;
	}
	
	/**
	 * 查询所有图书
	 * @return
	 */
	public List<Book> getBooks(){
		return books;
	}
}
